import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
// import SLIDELOCK from '@/components/SlideLock';
//图片
// no-find-blur.png
import noFindBlur from '@/assets/icon/no-find-blur.png';
import noFindFocus from '@/assets/icon/no-find-focus.png';
import processBlur from '@/assets/icon/process-blur.png';
import processFocus from '@/assets/icon/process-focus.png';
import subBlur from '@/assets/icon/sub-blur.png';
import subFocus from '@/assets/icon/sub-focus.png';
import allFocus from '@/assets/icon/all-focus.png';
import allBlur from '@/assets/icon/all-blur.png';
import finishBlur from '@/assets/icon/finish-blur.png';
import finishFocus from '@/assets/icon/finish-focus.png';
import errFocus from '@/assets/icon/err-focus.png';
import errBlur from '@/assets/icon/err-blur.png';
import hichainLogo from '@/assets/hichainLogo.png';
import defaultPic from '@/assets/icon/defaultPic.png';
import defaultAtt from '@/assets/icon/defaultAtt.png';

import router from 'umi/router';
import {
  Card,
  Row,
  Col,
  Icon,
  Avatar,
  Tag,
  Divider,
  Spin,
  Input,
  Select,
  Button,
  Collapse,
  Timeline,
  Form,
  Slider,
  Modal,
  Table,
  notification,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import moment from 'moment';
import styles from './Trail.less';
import { relative } from 'path';
import { statusTrailList, renderTableAdSelect } from './utils';

function changeViewPort(key, val) {
  var reg = new RegExp(key, 'i'),
    oldval = document.querySelector('meta[name="viewport"]').content;
  var newval = reg.test(oldval)
    ? oldval
        .split(/,\s*/)
        .map(function(v) {
          return reg.test(v) ? key + '=' + val : v;
        })
        .join(', ')
    : (oldval += ', ' + key + '=' + val);
  document.querySelector('meta[name="viewport"]').content = newval;
}
// 检查是否为移动端（true）
var isIphone = true;
function detectmo() {
  if (
    navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/BlackBerry/i) ||
    navigator.userAgent.match(/Windows Phone/i)
  ) {
    return true;
  } else {
    return false;
  }
}

const FormItem = Form.Item;
const Panel = Collapse.Panel;
var clickdelay = 0;
//定义获取方法
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
// 提示窗
function openNotification(message) {
  notification.open({
    message: '温馨提示',
    duration: 2,
    description: message,
    onClick: () => {
      console.log('Notification Clicked!');
    },
  });
}

@connect(({ trail, loading }) => ({
  trail,
  loading: loading.models.trail,
}))
@Form.create()
class Trail extends PureComponent {
  constructor(props) {
    super(props);
  }

  state = {
    newTags: [],
    firstImgStatu: 1,
    inputVisible: false,
    tabCardKey: '',
    formValues: {},
    restNumber: 40,
    toggle: false,
    toggleBack: false,
    value: [],
    stateImg: [
      allBlur,
      allFocus,
      noFindBlur,
      noFindFocus,
      subBlur,
      subFocus,
      processBlur,
      processFocus,
      finishBlur,
      finishFocus,
      errBlur,
      errFocus,
    ],
    stateIndex: [0, 2, 4, 6, 8, 10],
    calNum: 0,
    visible: false,
    showFileUrl: '',
    timerline: '',
    inputToggle: true,
  };

  // 图片放大
  debugger;
  showModal = showFileUrl => {
    this.setState({
      visible: true,
      showFileUrl: showFileUrl,
    });
  };
  handleOk = e => {
    this.setState({
      visible: false,
    });
  };
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'trail/setData',
    });
  }
  //滑块判断通过
  // slideLock = () => {
  //   this.setState({
  //     toggle: true,
  //   });
  // };

  // 重置滑块
  onRef = ref => {
    this.child = ref;
  };
  // resetLock = e => {
  //   this.child.lockreset();
  // };

  //处理搜索时的操作
  handleSearch = e => {
    //防止快速点击
    var timerOrign = new Date();
    timerOrign = timerOrign.getTime();
    if (this.state.timerline) {
      if (timerOrign - this.state.timerline < 1000) {
        openNotification('点击过快');
        return;
      }
    }

    //内容为空
    if (this.state.restNumber > 39) {
      openNotification('查询内容不能为空');
      return;
    }

    //滑块验证
    // if (!this.state.toggle) {
    //   openNotification('请先完成滑块验证');
    //   return;
    // }
    //标题切换
    // if ($('.logoTop')) {
    //   this.refs.logoTop.style.display = 'none';
    //   $('.header-top').css('display', 'flex');
    //   this.refs.wrap.style.top = 0;
    // }
    //重置滑块
    // this.resetLock();
    let number = this.state.restNumber;
    e.preventDefault();
    const { inputVisible, tabCardKey } = this.state;
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };

      this.setState({
        formValues: values,
        tabCardKey: tabCardKey,
        inputVisible: true,
        toggle: false,
        timerline: timerOrign,
      });
      dispatch({
        type: 'trail/queryCode',
        payload: values,
      });
      // .then(() => {
      //   this.phonedisplay();
      //   //=========================
      // });
    });
  };

  // =================页面调整
  phonedisplay = () => {
    var _this = this;
    if (!detectmo()) {
      isIphone = false;
      return;
    }
    this.refs.boxwrap.style.overflow = 'scroll';
    $(this.refs.box).css({
      width: '11rem',
    });
    this.refs.addressNode.scrollIntoView();
  };
  //======================地址搜索
  search = queryValues => {
    var values = queryValues;
    const { inputVisible, tabCardKey } = this.state;
    const { dispatch, form } = this.props;
    this.setState({
      formValues: values,
      tabCardKey: tabCardKey,
      inputVisible: true,
    });
    dispatch({
      type: 'trail/queryCode',
      payload: values,
    });
  };
  // 标题栏切换
  onCardTabChange = key => {
    console.log('==========', key);
    var index = 0;
    switch (key) {
      case 'queryAllResultKey':
        index = 0;
        break;
      case 'queryNotKey':
        index = 1;
        break;
      case 'querySubmitKey':
        index = 2;
        break;
      case 'queryProcessKey':
        index = 3;
        break;
      case 'queryFinishKey':
        index = 4;
        break;
      case 'queryExceptionKey':
        index = 5;
        break;
      default:
        break;
    }

    this.setState({
      tabCardKey: key,
      stateIndex: [0, 2, 4, 6, 8, 10],
      firstImgStatu: 0,
    });
    var stateMock = [0, 2, 4, 6, 8, 10];
    stateMock.splice(index, 1, stateMock[index] + 1);
    this.setState({
      stateIndex: stateMock,
    });
  };

  componentDidMount() {
    document.documentElement.scrollTop = 0;
    // 限制查询数<0
    if (this.state.restNumber <= 0) {
      this.setState({
        restNumber: 0,
      });
    }
    // 地址搜索
    if (this.props.location.search) {
      var searchValues = this.props.location.search;
      searchValues = searchValues.split('?')[1].split('=')[1];
      searchValues = decodeURI(searchValues);
      searchValues = searchValues.replace(/，/gi, ',');
      searchValues = searchValues.split(',');
      searchValues = new Set(searchValues);
      searchValues = Array.from(searchValues);
      if (searchValues.length > 40) {
        searchValues = searchValues.splice(0, 40);
      }
      searchValues = { orderNo: searchValues };
      this.search(searchValues);
      //标题切换
      //   if ($('.logoTop')) {
      //     this.refs.logoTop.style.display = 'none';
      //     $('.header-top').css('display', 'flex');
      //     this.refs.wrap.style.top = 0;
      //   }
    } else {
      // $('.header-top').css('display', 'none');
    }
  }
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Card bordered={false} style={{ marginBottom: 24, backgroundColor: '#fff' }}>
        <Form layout="inline">
          {getFieldDecorator('orderNo', {
            initialValue: this.state.value,
          })(
            <Select
              showSearch={false}
              mode="tags"
              placeholder={'多个单号支持回车，TAB，空格，逗号分隔单号'}
              allowClear={true}
              maxTagCount={40}
              notFoundContent={'请输入物流单号'}
              // open={false}
              dropdownStyle={{ display: 'none' }}
              style={{ width: '100%' }}
              className={styles.customSelect}
              onChange={value => {
                value.splice(40);
                this.setState({
                  restNumber: 40 - value.length,
                  value,
                });
              }}
              tokenSeparators={[',', '，', ' ', '\n', '\t']}
            />
          )}
          <div className={styles.restNumber}>还可以输入{this.state.restNumber}条订单号</div>
          {/* <Divider dashed /> */}
          <div className={styles.avatarHolder}>
            {/* <SLIDELOCK toggle={this.slideLock.bind(this)} onRef={this.onRef.bind(this)} /> */}
            <div ref={'addressNode'} style={{ height: 1 }} />
            <Button
              id="divNode"
              ref={'divNode'}
              style={{ width: '100%' }}
              onClick={this.handleSearch}
              size={'large'}
              type="primary"
            >
              查询
            </Button>
            {/* <div style={{ marginTop: 20 }}>
              <Link to="/queryVipTracking">
                <span style={{ fontSize: 16 }}>跳转到大客户单号查询</span>
                <Icon type="right" />
              </Link>
            </div> */}
          </div>
        </Form>
      </Card>
    );
  }
  toggle = () => {
    this.setState({ inputToggle: !this.state.inputToggle });
  };

  //缩略图
  thumbnailDom = data => {
    return data.map((trackFile, value1) => {
      if (trackFile.fileType === 'jpg' || trackFile.fileType === 'png') {
        return (
          <a style={{ marginRight: 5 }} onClick={() => this.showModal(trackFile.fileUrl)}>
            <img
              src={defaultPic}
              style={{
                width: 30,
                height: 20,
              }}
              refs={value1}
            />
          </a>
        );
      } else {
        return (
          <a style={{ marginRight: 5 }} href={trackFile.fileUrl} target="_blank" download="">
            <img
              src={defaultAtt}
              style={{
                width: 30,
                height: 20,
              }}
            />
          </a>
        );
      }
    });
  };

  //时间线
  timelineDom = data => {
    if (data.length > 0) {
      return data.map((item1, index) => {
        return (
          <Timeline.Item key={index}>
            <div
              style={{
                color: index == 0 ? 'red' : 'black',
              }}
              className={styles.timeLineBox}
            >
              <div className={styles.trailTime}>
                {moment(item1.eventTime).format('YYYY/MM/DD HH:mm')}
              </div>
              <div title={item1.eventDesc} className={styles.trailInfo}>
                {item1.eventDesc}
              </div>
              <div className={styles.trailFile}>
                {item1.trackFiles && this.thumbnailDom(item1.trackFiles)}
              </div>
              <div title={item1.remarks} className={styles.trailRemark}>
                {item1.remarks}
              </div>
              <div className={styles.trailBeShow}>{item1.beShow === '1' ? '公开' : '内部'}</div>
              <div className={styles.traileventSource}>{item1.eventSource}</div>
              <div className={styles.trailOperator}>{item1.operator}</div>
              <div className={styles.trailHandoverPerson}>{item1.handoverPerson}</div>
            </div>
          </Timeline.Item>
        );
      });
    } else {
      return <div>暂无轨迹信息</div>;
    }
  };

  showContentDom = showContent => {
    if (showContent.length === 0) return;
    return showContent.map((item, value) => {
      return (
        <Panel
          style={{ background: '#FFFFFF' }}
          forceRender={true}
          disabled={item['bizStatus'] != 'NOT' ? false : true}
          key={value + 1}
          header={
            <div style={{ width: '100%', display: 'flex' }}>
              <div style={{ width: '18%' }}>
                <div
                  style={{
                    color: 'rgb(24, 144, 255)',
                    height: '20px',
                    width: '80%',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {item['orderNo']}
                </div>
                {renderTableAdSelect({
                  props: this.props,
                  value: item.bizStatus,
                  data: statusTrailList,
                })}
              </div>
              <div style={{ width: '20%', overflow: 'hidden' }}>
                <p className={styles.textPoint} style={{ width: '80%' }}>
                  {item['vipOrderNo']}
                </p>
              </div>
              <div style={{ width: '22%', overflow: 'hidden' }}>
                <p className={styles.textPoint} style={{ width: '80%' }}>
                  {item['estimatedArrivalTime']
                    ? item['estimatedArrivalTime']
                        .split(':')
                        .slice(0, -1)
                        .join(':')
                    : ''}
                </p>
              </div>

              {item.orderTracking ? (
                Array.isArray(item.orderTracking) &&
                item.orderTracking.length > 0 && (
                  <div
                    style={{
                      fontSize: 14,
                      width: '35%',
                    }}
                    className={styles.textsPoint}
                  >
                    {moment(item['orderTracking'][0].eventTime).format('YYYY/MM/DD HH:mm')}
                    &nbsp;&nbsp;&nbsp;
                    {item['orderTracking'][0].eventDesc}
                  </div>
                )
              ) : (
                <div
                  style={{
                    overflow: 'hidden',
                    height: '0.52rem',
                    width: '20%',
                    flex: 1,
                  }}
                />
              )}
            </div>
          }
        >
          <div className={`${styles.lineTitle} ${styles.timeLineBox}`}>
            <div className={styles.trailTime}>轨迹时间</div>
            <div className={styles.trailInfo}>轨迹信息</div>
            <div className={styles.trailFile}>凭证</div>
            <div className={styles.trailRemark}>备注</div>
            <div className={styles.trailBeShow}>是否公开</div>
            <div className={styles.traileventSource}>来源</div>
            <div className={styles.trailOperator}>操作人</div>
            <div className={styles.trailHandoverPerson}>交接人</div>
          </div>
          <Timeline>
            {item.orderTracking &&
              Array.isArray(item.orderTracking) &&
              this.timelineDom(item.orderTracking)}
          </Timeline>
        </Panel>
      );
    });
  };

  render() {
    const Panel = Collapse.Panel;
    const { newTags, inputVisible, formValues, tabCardKey, inputToggle } = this.state;
    const {
      trail: { data },
      loading,
    } = this.props;

    const operationTabList = [];
    let tempCardKey = tabCardKey;
    let tempContent = [];
    //第一次加载临时标识
    let tempFlag = false;

    //全部结果
    //全部
    let queryAllResult = [];
    //查询不到
    let queryNot = [];
    //已提交
    let querySubmit = [];
    //进行中
    let queryProcess = [];
    //已完成
    let queryFinish = [];
    //异常
    let queryException = [];
    //需要显示的内容
    let showContent = [];

    let orderResult;
    if (data != null && data.orderResult != null) {
      orderResult = data.orderResult;
      //找到查询不到的结果
      if (formValues.orderNo) {
        for (let formValue of formValues.orderNo) {
          let existFlag = false;
          if (orderResult.data.list != null) {
            for (let orderResultContent of orderResult.data.list) {
              if (
                formValue === orderResultContent.orderNo ||
                formValue === orderResultContent.vipOrderNo ||
                (orderResultContent.vipOrderNo &&
                  orderResultContent.vipOrderNo.split('/').includes(formValue))
              ) {
                existFlag = true;
                break;
              }
            }
          }
          if (!existFlag) {
            queryNot.push({
              orderNo: formValue,
              customerOrderNo: '-',
              customerName: '-',
              bizStatus: 'NOT',
            });
          }
        }
      }
      if (orderResult.data && orderResult.data.list != null) {
        //根据查询结果分组数据
        for (let orderResultContent of orderResult.data.list) {
          if (orderResultContent.orderNo != null) {
            queryAllResult.push(orderResultContent);
            if ('NOT' === orderResultContent.bizStatus) {
              queryNot.push(orderResultContent);
            } else if ('SUBMIT' === orderResultContent.bizStatus) {
              querySubmit.push(orderResultContent);
            } else if ('PROCESS' === orderResultContent.bizStatus) {
              queryProcess.push(orderResultContent);
            } else if ('FINISHED' === orderResultContent.bizStatus) {
              queryFinish.push(orderResultContent);
            } else if ('EXCEPTION' === orderResultContent.bizStatus) {
              queryException.push(orderResultContent);
            }
          }
        }
      }

      if (tempCardKey === null || tempCardKey === '') {
        tempFlag = true;
        tempCardKey = 'queryAllResultKey';
      }

      if (tempFlag || 'queryAllResultKey' === tempCardKey) {
        showContent = showContent.concat(queryAllResult);
        showContent = showContent.concat(queryNot);
      } else if ('queryNotKey' === tempCardKey) {
        showContent = showContent.concat(queryNot);
      } else if ('querySubmitKey' === tempCardKey) {
        showContent = showContent.concat(querySubmit);
      } else if ('queryProcessKey' === tempCardKey) {
        showContent = showContent.concat(queryProcess);
      } else if ('queryFinishKey' === tempCardKey) {
        showContent = showContent.concat(queryFinish);
      } else if ('queryExceptionKey' === tempCardKey) {
        showContent = showContent.concat(queryException);
      }
    }
    operationTabList.push({
      key: 'queryAllResultKey',
      tab: (
        <span>
          <img
            src={
              this.state.firstImgStatu == 1
                ? this.state.stateImg[1]
                : this.state.stateImg[this.state.stateIndex[0]]
            }
            style={{ width: '1.8rem', height: '1.8rem', position: 'relative', top: '-3px' }}
          />
          全部
          <span style={{ fontSize: '0.14rem' }}>({queryAllResult.length + queryNot.length})</span>
        </span>
      ),
    });
    operationTabList.push({
      key: 'queryNotKey',
      tab: (
        <span>
          <img
            src={this.state.stateImg[this.state.stateIndex[1]]}
            style={{ width: '1.8rem', height: '1.8rem', position: 'relative', top: '-3px' }}
          />
          查询不到 <span style={{ fontSize: '0.14rem' }}>({queryNot.length})</span>
        </span>
      ),
    });

    operationTabList.push({
      key: 'querySubmitKey',
      tab: (
        <span>
          <img
            src={this.state.stateImg[this.state.stateIndex[2]]}
            style={{ width: '1.8rem', height: '1.8rem', position: 'relative', top: '-3px' }}
          />
          已提交 <span style={{ fontSize: '0.14rem' }}>({querySubmit.length})</span>
        </span>
      ),
    });

    operationTabList.push({
      key: 'queryProcessKey',
      tab: (
        <span>
          <img
            src={this.state.stateImg[this.state.stateIndex[3]]}
            style={{ width: '1.8rem', height: '1.8rem', position: 'relative', top: '-3px' }}
          />
          进行中 <span style={{ fontSize: '0.14rem' }}>({queryProcess.length})</span>
        </span>
      ),
    });

    operationTabList.push({
      key: 'queryFinishKey',
      tab: (
        <span>
          <img
            src={this.state.stateImg[this.state.stateIndex[4]]}
            style={{ width: '1.8rem', height: '1.8rem', position: 'relative', top: '-2px' }}
          />
          已完成 <span style={{ fontSize: '0.14rem' }}>({queryFinish.length})</span>
        </span>
      ),
    });

    operationTabList.push({
      key: 'queryExceptionKey',
      tab: (
        <span>
          <img
            src={this.state.stateImg[this.state.stateIndex[5]]}
            style={{ width: '1.8rem', height: '1.8rem' }}
          />
          异常 <span style={{ fontSize: '0.14rem' }}>({queryException.length})</span>
        </span>
      ),
    });
    var aa = 10;
    var _this = this;

    let imgFile = [];
    return (
      <div className={`${styles.xj} ${styles.cus_timeLineBox}`} ref={'wrap'}>
        {/* <div className={styles.logoTop} ref={'logoTop'}>
          <img src={hichainLogo} />
          <h2>海晨物流跟踪平台</h2>
        </div> */}
        <GridContent className={styles.userCenter}>
          {/* <Row gutter={24}>
            <Col lg={8} md={24} />
            <Col lg={8} md={24}>
              {this.renderSimpleForm()}
            </Col>
            <Col lg={8} md={24} />
          </Row> */}
          <Row gutter={24}>
            {inputToggle && (
              <Col lg={5} md={24}>
                {this.renderSimpleForm()}
              </Col>
            )}

            <Col lg={inputToggle ? 19 : 24} md={24}>
              <div ref={'boxwrap'} className={styles.contentBottom}>
                <div className={styles.toggleView}>
                  <Icon
                    className={styles.toggle}
                    onClick={this.toggle}
                    type={inputToggle ? 'menu-unfold' : 'menu-fold'}
                    style={{ marginLeft: 8 }}
                  />
                </div>
                <div ref={'box'} className={styles.contentDisplay}>
                  <Card
                    className={styles.tabsCard}
                    bordered={false}
                    tabList={operationTabList}
                    defaultActiveTabKey={'0'}
                    onTabChange={this.onCardTabChange}
                    loading={false}
                  >
                    <div
                      className={styles.listMenu}
                      style={{
                        height: '3rem',
                        width: '100%',
                        overflow: 'hidden',
                        fontWeight: 800,
                        fontSize: '0.14rem',
                        lineHeight: '3rem',
                        backgroundColor: '#FBFBFB',
                        border: '1px solid #D5D5D5',
                        borderBottom: 'none',
                        borderRadius: '2px',
                      }}
                    >
                      <div>订单号</div>
                      <div>客户单号</div>
                      <div>预计到达时间</div>
                      <div>最新轨迹</div>
                    </div>
                    <Collapse onChange={this.handleChange} style={{ overflow: 'hidden' }}>
                      {showContent && showContent.length > 0 && this.showContentDom(showContent)}
                    </Collapse>
                    <Modal
                      footer={null}
                      onOk={_this.handleOk}
                      onCancel={_this.handleCancel}
                      visible={_this.state.visible}
                      width={1000}
                      centered
                      maskStyle={{ opacity: 0.1, backgroundColor: '#666' }}
                    >
                      <div style={{ height: 500, overflowY: 'auto', marginTop: 20 }}>
                        <img
                          src={_this.state.showFileUrl}
                          style={{
                            width: '80%',
                            height: 'auto',
                            margin: '0 auto',
                            display: 'block',
                          }}
                        />
                      </div>
                    </Modal>
                  </Card>
                </div>
              </div>
            </Col>
          </Row>
        </GridContent>
      </div>
    );
  }
}

export default Trail;
